#region Copyright (c) 2006-2009 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2009 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion
using System;
using System.Collections;
using Widgetsphere.Generator.Common.GeneratorFramework;
using System.Windows.Forms;
using Widgetsphere.Generator.Common.Util;
using System.Xml;
using System.Collections.Generic;

namespace Widgetsphere.Generator.Models
{
	public class TableController : BaseModelObjectController
	{
		#region Member Variables

		#endregion

    #region Constructor

    protected internal TableController(IModelObject modelObject)
      : base(modelObject)
    {
    }

    #endregion

		#region BaseModelObjectController Members

		public override ModelObjectTreeNode Node
		{
			get
			{
				if(_node == null)
				{
					_node = new TableNode(this);
				}
				return _node;
			}
		}

    public override MenuCommand[] GetMenuCommands()
    {
      MenuCommand menuDelete = new DefaultMenuCommand();
			menuDelete.Text = "Delete";
			menuDelete.Click += new EventHandler(DeleteMenuClick);

			MenuCommand menuSep = new DefaultMenuCommand();
			menuSep.Text = "-";

			MenuCommand menuCopy = new DefaultMenuCommand();
			menuCopy.Text = "Copy";
			menuCopy.Click += new EventHandler(CopyMenuClick);

			MenuCommand menuSep2 = new DefaultMenuCommand();
			menuSep2.Text = "-";

			MenuCommand mcAddUnitTest = new DefaultMenuCommand();
			mcAddUnitTest.Text = "Add Unit Tests";
			mcAddUnitTest.Click += new EventHandler(AddUnitTestMenuClick);

			return new MenuCommand[] { menuDelete, menuSep, menuCopy, menuSep2, mcAddUnitTest };
    }

    public override MessageCollection Verify()
    {
      try
      {
        MessageCollection retval = new MessageCollection();
        retval.AddRange(base.Verify());

				Table table = (Table)this.Object;

				#region Remove invalid columns
				List<Relation> deleteRelationList = new List<Relation>();
				foreach (Relation relation in ((ModelRoot)table.Root).Database.Relations)
				{
					if (relation.ParentTableRef == null)
						deleteRelationList.Add(relation);
					else if (relation.FkColumns.Count == 0)
						deleteRelationList.Add(relation);
					else if (relation.ChildTableRef == null)
						deleteRelationList.Add(relation);
					else if (relation.FkColumns.Count == 0)
						deleteRelationList.Add(relation);
					else
					{
						foreach (Relation tempRelation in ((Table)relation.ChildTableRef.Object).ChildRoleRelations)
						{
							if (tempRelation.ChildTableRef == null)
								deleteRelationList.Add(relation);
							else if (tempRelation.ChildTableRef.Object == null)
								deleteRelationList.Add(relation);
							else if (tempRelation.ParentTableRef == null)
								deleteRelationList.Add(relation);
							else if (tempRelation.ParentTableRef.Object == null)
								deleteRelationList.Add(relation);
						}

						for (int ii = 0; ii < relation.FkColumns.Count; ii++)
						{
							if (((Column)relation.FkColumns[ii]).ParentTableRef == null)
								deleteRelationList.Add(relation);
						}
					}
				}
				#endregion

				if (table.Generated)
				{
					#region Check valid name
					if (!ValidationHelper.ValidDatabaseIdenitifer(table.DatabaseName))
						retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextInvalidIdentifier, table.Name), this);
					if (!ValidationHelper.ValidCodeIdenitifer(table.PascalName))
						retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextInvalidIdentifier, table.Name), this);
					#endregion

					#region Check that non-key relationships have a unique index on fields
					foreach (Reference reference in table.Relationships)
					{
						Relation relation = (Relation)reference.Object;
						if (!relation.IsPrimaryKeyRelation())
						{
							foreach (ColumnRelationship columnRelationship in relation.ColumnRelationships)
							{
								Column parentColumn = (Column)columnRelationship.ParentColumnRef.Object;
								if (!parentColumn.IsUnique)
									retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextTableColumnNonPrimaryRelationNotUnique, parentColumn.DatabaseName, table.Name), this);
							}
						}
					}
					#endregion

					#region Verify that type tables have data
					if (table.IsTypeTable)
					{
						if (table.StaticData.Count == 0)
							retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextTypeTableNoData, table.CodeFacade), this);
					}
					#endregion

					#region Unit tests cannot be performed on base tables
					if (table.AllowUnitTest != Table.UnitTestSettingsConstants.StubOnly)
					{
						if (!table.AllowModification)
						{
							retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextTableDoesNotAllowModification, table.PascalName), this);
						}
					}
					#endregion

					#region Check that object has at least one generated column
          if(table.GeneratedColumns.Count == 0)
            retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextColumnsRequired, this);
					#endregion

					#region Clean up bogus references (in case this happened)
					ArrayList delReferences = new ArrayList();

					//Verify that no column has same name as table
					foreach (Reference reference in table.Columns)
					{
						Column column = (Column)reference.Object;
						if (string.Compare(column.Name, table.Name, true) == 0)
						{
							retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextTableColumnNameMatch + " (" + column.ToString() + ")", this);
						}
					}

          //Verify relationships
          foreach(Reference reference in table.Relationships)
          {
            Relation relation = (Relation)reference.Object;
            if(relation != null)
            {
							foreach (ColumnRelationship cRel in relation.ColumnRelationships)
							{
								Column c1 = (Column)cRel.ParentColumnRef.Object;
								Column c2 = (Column)cRel.ChildColumnRef.Object;
								if (c1.Type != c2.Type)
								{
									retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextRelationshipTypeMismatch + " (" + c1.ToString() + " -> " + c2.ToString() + ")", this);
								}
							}

            }
          }

          //Remove old relations
          foreach(Reference reference in delReferences)
          {
            table.Relationships.Remove(reference);
          }

					//Verify that inheritance is setup correctly
					if (!table.IsValidInheritance)
					{
						retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextInvalidInheritance, table.Name), this);
					}

					#endregion

					#region Check that table does not have same name as project

					if (table.PascalName == ((ModelRoot)table.Root).ProjectName)
					{
						retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextTableProjectSameName, table.PascalName), this);
					}

					#endregion

					#region Type tables should really be immutable

					if (table.IsTypeTable && table.AllowModification)
					{
						retval.Add(MessageTypeConstants.Warning, string.Format(ValidationHelper.ErrorTextTypeTableIsWritable, table.PascalName), this);
					}

					#endregion

					#region Check for classes that will confict with generated classes

					List<string> classExtensions = new List<string>();
					classExtensions.Add("collection");
					classExtensions.Add("enumerator");
					classExtensions.Add("query");
					classExtensions.Add("search");
					classExtensions.Add("pagingfielditem");
					classExtensions.Add("paging");
					classExtensions.Add("primarykey");
					classExtensions.Add("selectall");
					classExtensions.Add("pagedselect");
					classExtensions.Add("selectbypks");
					classExtensions.Add("selectbycreateddaterange");
					classExtensions.Add("selectbymodifieddaterange");
					classExtensions.Add("selectbysearch");
					classExtensions.Add("beforechangeeventargs");
					classExtensions.Add("afterchangeeventargs");

					foreach (string ending in classExtensions)
					{
						if (table.Name.ToLower().EndsWith(ending))
						{
							retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextNameConfictsWithGeneratedCode, table.Name), this);
						}
						else if (table.PascalName.ToLower().EndsWith(ending))
						{
							retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextNameConfictsWithGeneratedCode, table.Name), this);
						}
					}

					#endregion


					#region Check for inherit heirarchy that all tables are modifiable or not modifiable

					//If this table is Mutable then make sure it is NOT derived from an Immutable table
					if (!table.Immutable)
					{
						List<Table> heirList = table.GetTableHierarchy();
						int immutableCount = 0;
						Table immutableTable = null;
						foreach (Table h in heirList)
						{
							if (h.Immutable)
							{
								if (immutableTable == null) immutableTable = h;
								immutableCount++;
							}
						}

						//If the counts are different then show errors
						if (immutableCount > 0)
						{
							retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextMutableInherit, table.Name, immutableTable.Name), this);
						}
					}

					#endregion

					#region Check that all tables in inheritance chain are generated

					{
						List<Table> heirList = table.GetTableHierarchy();
						int nonGenCount = 0;
						Table nonGenTable = null;
						foreach (Table h in heirList)
						{
							if (!h.Generated)
							{
								if (nonGenTable == null) nonGenTable = h;
								nonGenCount++;
							}
						}

						//If the counts are different then show errors
						if (nonGenCount > 0)
						{
							retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextBaseTableNonGenerated, nonGenTable.Name, table.Name), this);
						}
					}

					#endregion

					#region Type Tables must be immutable

					if (table.IsTypeTable & !table.Immutable)
						retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextTypeTableIsMutable, table.Name), this);

					#endregion

					#region Verify Relations

					foreach (Reference reference in table.Relationships)
					{
						Relation relation = (Relation)reference.Object;
						Table parentTable = (Table)relation.ChildTableRef.Object;
						Table childTable = (Table)relation.ParentTableRef.Object;
						foreach (ColumnRelationship columnRelationship in relation.ColumnRelationships)
						{
							Column childColumn = (Column)columnRelationship.ChildColumnRef.Object;
							Column parentColumn = (Column)columnRelationship.ParentColumnRef.Object;
							if (parentColumn.Identity == IdentityTypeConstants.Database)
							{
								if (childColumn.Identity == IdentityTypeConstants.Database)
								{
									retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextChildTableRelationIdentity, parentTable.Name, childTable.Name), this);
								}
							}
						}
					}

					#endregion

				}

        return retval;

      }
      catch (Exception ex)
      {
        throw;
      }

    }

    public override bool DeleteObject()
    {
      if(MessageBox.Show("Do you wish to delete this table?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
      {
        ((ModelRoot)this.Object.Root).Database.Tables.Remove(((Table)this.Object).Id);
        this.Node.Remove();
        this.Object.Root.Dirty = true;
        return true;
      }
      return false;
    }

    public override void Refresh()
    {
    }

		#endregion

		#region Menu Handlers

		private void AddUnitTestMenuClick(object sender, System.EventArgs e)
		{
			Table table = (Table)this.Object;
			{
				table.AddUnitTests();
			}
			this.OnItemChanged(this, new System.EventArgs());
		}	

    private void DeleteMenuClick(object sender, System.EventArgs e)
    {
      this.DeleteObject();
    }

		private void CopyMenuClick(object sender, System.EventArgs e)
		{
			XmlDocument document = new XmlDocument();
			document.LoadXml("<a></a>");

			//Add a table node
			XmlNode tableNode = document.CreateElement("table");
			((Table)this.Object).XmlAppend(tableNode);
			document.DocumentElement.AppendChild(tableNode);

			//Add the columns
			XmlNode columnListNode = document.CreateElement("columnList");
			document.DocumentElement.AppendChild(columnListNode);
			foreach (Reference reference in ((Table)this.Object).Columns)
			{
				XmlNode columnNode = document.CreateElement("column");
				((Column)reference.Object).XmlAppend(columnNode);
				columnListNode.AppendChild(columnNode);
			}			

			Clipboard.SetData("ws.model.table", document.OuterXml);

		}

		#endregion

	}
}